package com.joker.order.interceptor;

import com.joker.common.core.utils.StringUtils;
import com.joker.common.redis.service.RedisService;
import com.joker.order.annotation.CheckIdempotent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class CheckIdempotentInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            //放行
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();
        CheckIdempotent checkIdempotent = method.getAnnotation(CheckIdempotent.class);

        if (checkIdempotent != null){
            try {
                return checkToken(request);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public boolean checkToken(HttpServletRequest request){

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw new RuntimeException("token不能为空");
        }

        boolean del = redisService.deleteObject(token);
        if (!del){
            throw new RuntimeException("token删除失败");
        }

        return true;
    }

}
